from django.shortcuts import redirect, render, HttpResponse, reverse
from django.db.models import Count
import collections
import time
import datetime
from django.http import JsonResponse

from web import models


def dashboard(request, project_id):
    """概览"""
    # 问题数据处理
    status_dict = collections.OrderedDict()
    for key, text in models.Issues.status_choices:
        status_dict[key] = {"text": text, "count": 0}
    """
        status_dict = {
            "1": {"text": "新建", "count": 0},
            "2": {"text": "处理中", "count": 1},
        }
    """

    # <QuerySet [{'status': 1, 'ct': 1}, {'status': 2, 'ct': 1}]>
    issues_data = models.Issues.objects.filter(project_id=project_id).values("status").annotate(ct=Count("id"))
    for item in issues_data:
        status_dict[item["status"]]["count"] = item["ct"]

    # 项目成员
    user_list = models.ProjectUser.objects.filter(project_id=project_id).values("user_id", "user__username")

    # 最近的10个操作记录
    top_ten = models.Issues.objects.filter(project_id=project_id, assign__isnull=False).order_by("-id")[:10]

    context = {
        "status_dict": status_dict,
        "user_list": user_list,
        "top_ten_object": top_ten,
    }

    return render(request, "dashboard.html", context)


def issues_chart(request, project_id):
    """在概览页面highcharts，问题数量图标展示"""
    date_dict = collections.OrderedDict()
    today = datetime.datetime.now()
    for i in range(30):
        date = today - datetime.timedelta(days=i)
        date_dict[date.strftime("%Y-%m-%d")] = [time.mktime(date.timetuple()) * 1000, 0]
        """
            date_dict = {
            "2021-3-19": ["2021-3-19的时间戳", "新增问题数量"]
        }
        """

    result = models.Issues.objects.filter(project_id=project_id, create_datetime__gte=today-datetime.timedelta(days=30)).extra(
        select={"ctime": "strftime('%%Y-%%m-%%d',web_issues.create_datetime)"}).values("ctime").annotate(ct=Count("id"))

    # print(result)
    """
        result = [
        {'ctime': '2021-03-17', 'ct': 3}, 
        {'ctime': '2021-03-19', 'ct': 1}
    ]
    """
    for item in result:
        date_dict[item["ctime"]][1] = item["ct"]

    # print(date_dict)

    return JsonResponse({"status": True, "data": list(date_dict.values())})